﻿using MaterialDesignThemes.Wpf;
using MySql.Data.MySqlClient;
using NewLife.Data;
using SkiaSharp;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using XingLucifer.IBase.Enums;
using static log4net.Appender.RollingFileAppender;

namespace UIWindows.Tools.Helper
{
    public class MySqlHelper
    {

        public MySqlHelper(string connString)
        {
            _connString = connString;
        }

        // string connString = "server=DESKTOP-BQDF638;database=test_four;uid=sa;pwd=123456";
        string _connString = "server=127.0.0.1;port=3306;user=root;password=admin999; database=weightdb;CharSet=utf8mb4;Allow User Variables=True;";

        MySqlConnection conn = null;
        public bool OpenDB()
        {
            int reConnectCount = 0;
        reConnecting:
            try
            {
                conn = new MySqlConnection(_connString);
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                 $"[数据库]：连接成功".RunLog(MessageLevelType.成功);
                Task.Delay(50).GetAwaiter().GetResult();
                return true;
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref reConnectCount);
                $"[取一注数据]：数据库连接异常：{ex.Message}".RunLog(MessageLevelType.错误);
                if (reConnectCount < 4)
                {
                    Task.Delay(100).GetAwaiter().GetResult();
                    goto reConnecting;
                }
                return false;
            }

        }
        public bool CloseDB()
        {
            try
            {
                if (conn != null && conn.State == ConnectionState.Open)
                {
                    conn.Close();
                    conn.Dispose();
                }
                // $"[数据库]：关闭成功".RunLog(MessageLevelType.成功);
                return true;
            }
            catch (Exception ex)
            {
                $"[取一注数据]：关闭数据库异常：{ex.Message}".RunLog(MessageLevelType.错误);
                return false;
            }

        }




        /// <summary>
        /// 获取一次注液数据
        /// </summary>
        /// <param name="barcod"></param>
        /// <returns></returns>
        public (bool status, double netWeight, double outputWeight) GetBatteryByCode(string barcode)
        {
            string errMsg = string.Empty;
            DateTime dateTime = DateTime.Now;
        repeat:
            try
            {
                if (OpenDB())
                {
                    string tableName = $"ProductionData_{dateTime:yyyy}{dateTime.GetQuarterly()}";
                    var cmdTxt = @$"SELECT NetWeight,OneAfterWeighing FROM {tableName} WHERE Barcode='{barcode}' ORDER BY TimeScanCodeBefore desc LIMIT 1";
                    var cmd = new MySqlCommand(cmdTxt, conn);
                    var reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        $"[取一注数据]条码：{barcode}，一注干重：{reader[0]?.ToString()},一注出站重量：{reader[1]?.ToString()}".RunLog(MessageLevelType.成功);
                        return (true,
                                double.TryParse(reader[0]?.ToString(), out double result1) ? result1 : 0.0d,
                                double.TryParse(reader[1]?.ToString(), out double result2) ? result2 : 0.0d);
                    } 
                    if (dateTime.ContrastTime())
                    {
                        dateTime = dateTime.AddDays(-10);
                        goto repeat;
                    }
                    errMsg = $"[取一注数据]条码：{barcode}，一注数据为空!";
                    $"[取一注数据]条码：{barcode}，一注数据为空!".MessageDialogs(MessageLevelType.警告, true, Enums.PopUpTypes.Global);
                    errMsg.RunLog(MessageLevelType.警告);
                    return (false, 0.0d, 0.0d);

                }

                errMsg = $"[取一注数据]条码：{barcode}，无法打开数据库!";
                $"[取一注数据]条码：{barcode}，无法打开数据库!".MessageDialogs(MessageLevelType.警告, true, Enums.PopUpTypes.Global);
                errMsg.RunLog(MessageLevelType.警告);
                return (false, 0.0d, 0.0d);
            }
            catch (Exception ex)
            {
                if (dateTime.ContrastTime())
                {
                    dateTime = dateTime.AddDays(-10);
                    goto repeat;
                }
                errMsg = $"[取一注数据]条码：{barcode}异常：{ex}";
                $"[取一注数据]条码：{barcode} 异常!".MessageDialogs(MessageLevelType.警告, true, Enums.PopUpTypes.Global);
                errMsg.RunLog(MessageLevelType.警告);
                return (false, 0.0d, 0.0d);
            }
            finally
            {
                CloseDB();
            }


        }
    }
}
